package com.hethongviet.vending.helper.call;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;
import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Utils;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class ListenPhoneCallService extends Service
{
	private static OnIncomingCall onIncomingCall = null;

	public ListenPhoneCallService()
	{
		super();
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}

	@Override
	public void onCreate()
	{
		super.onCreate();
		try
		{
			StateListener phoneStateListener = new StateListener();
			TelephonyManager telephonymanager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			telephonymanager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		} catch (Exception e)
		{
		}

	}

	public static void setOnIncomingCall(OnIncomingCall incomingCall)
	{
		onIncomingCall = incomingCall;
	}
	
	class StateListener extends PhoneStateListener
	{
		@Override
		public void onCallStateChanged(int state, String incomingNumber)
		{
			Utils.debug("Receiver call!!!!!!!!!!!!!!!!!");
			
			super.onCallStateChanged(state, incomingNumber);
			
			switch (state)
			{
				case TelephonyManager.CALL_STATE_RINGING:
					Utils.debug("Receiver call!!!!!!!!!!!!!!!!!CALL_STATE_RINGING");
					try
					{
						TelephonyManager manager = (TelephonyManager) getApplication().getSystemService(Context.TELEPHONY_SERVICE);
						Class<?> managerClass = Class.forName(manager.getClass().getName());
						Method methodGetITelephony = managerClass.getDeclaredMethod("getITelephony");
						methodGetITelephony.setAccessible(true);
						ITelephony telephony = (ITelephony) methodGetITelephony.invoke(manager);
						telephony.endCall();
					} catch (Exception e)
					{
						e.printStackTrace();
					}

					if (incomingNumber != null && AppMain.getInstance().isStandbyScreen() && onIncomingCall != null) {
						Utils.debug("Receiver call!!!!!!!!!!!!!!!!! number = " + incomingNumber);
						onIncomingCall.onIncomingCall(incomingNumber);
					}

					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					// mute the call
					//telephony.setMute(true);
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					break;
			}
		}
	};

	@Override
	public void onDestroy()
	{

	}

}
